package uk.ac.cam.echo.app;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.tech.NfcV;
import android.widget.Toast;

/**
 * @author Vladimir Kovalev
 */
public class Scanner
{
	private final IntentFilter[] mFilters;
	private final String[][] mTechLists;
	private final PendingIntent mPendingIntent;
	private final NfcAdapter mAdapter = NfcAdapter.getDefaultAdapter();
	private final Activity caller;
	public boolean isActive = false;

	public Scanner(Activity _caller)
	{
		caller = _caller;
		IntentFilter mIntentFilter = new IntentFilter(NfcAdapter.EXTRA_TAG);
		try
		{
			mIntentFilter.addDataType("*/*");
		}
		catch (MalformedMimeTypeException e)
		{
			// TODO: handle exception
		}

		mFilters = new IntentFilter[] { mIntentFilter, };
		mTechLists = new String[][] { new String[] { NfcV.class.getName() } };
		mPendingIntent = PendingIntent.getActivity(caller, 0, new Intent(caller, caller.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		if (!mAdapter.isEnabled())
		{
			caller.runOnUiThread(new Runnable()
			{

				@Override
				public void run()
				{
					Toast.makeText(caller, "Please activate NFC and press Back to return to the application!", Toast.LENGTH_LONG).show();
					caller.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
				}
			});
		}
	}

	public void startSniffing()
	{
		mAdapter.enableForegroundDispatch(caller, mPendingIntent, mFilters, mTechLists);
		isActive = true;
	}

	public void stopSniffing()
	{
		mAdapter.disableForegroundDispatch(caller);
		isActive = false;
	}

	public void pause()
	{
		mAdapter.disableForegroundDispatch(caller);
	}

	public void resume()
	{
		if (isActive)
			mAdapter.enableForegroundDispatch(caller, mPendingIntent, mFilters, mTechLists);
	}

	public static String decode(Intent intent)
	{
		byte[] data = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);

		if (data == null)
			return null;

		StringBuffer hex = new StringBuffer();
		String zeroTest;
		for (int i = data.length - 1; i >= 0; i--)
		{
			zeroTest = Integer.toHexString(0xFF & data[i]);
			if (zeroTest.length() == 1)
			{
				hex.append('0');
			}
			hex.append(zeroTest.toUpperCase());
		}
		String tag = hex.toString();
		return tag;
	}
}
